package com.monolithiot.huawei.util;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

/**
 * 2019/1/9 Create by 郭文梁
 * HttpUtils
 * Http工具类
 *
 * @author 郭文梁
 * @date 2019/1/9
 */
public class HttpUtils {
    private static CloseableHttpClient client;

    static {
        createNewHttpClient();
    }

    private static void createNewHttpClient() {
        client = HttpClients.createDefault();
    }

    /**
     * 发送POST请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param body    请求体
     * @return Response body as string
     * @throws IOException IOE
     */
    public static String post(String url, List<Header> headers, String body) throws IOException {
        HttpPost post = new HttpPost(url);
        if (headers != null) {
            for (Header header : headers) {
                post.addHeader(header);
            }
        }
        post.setEntity(new StringEntity(body));
        CloseableHttpResponse response = null;
        String responseString = null;
        try {
            response = client.execute(post);
            int responseStatusCode = response.getStatusLine().getStatusCode();
            if (responseStatusCode == HttpStatus.SC_OK) {
                responseString = EntityUtils.toString(response.getEntity());
            } else {
                logError("Could not execute http post, Response status :" + responseStatusCode);
                logError("Response body:" + EntityUtils.toString(response.getEntity()));
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseString;
    }

    /**
     * 打印错误日志
     *
     * @param msg 输出内容
     */
    private static void logError(String msg) {
        System.err.println(msg);
    }
}
